package com.jahentao.patentQuery.util;

import com.jahentao.patentQuery.model.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

/**
 * PasswordHelper 的加密方式要和Shiro配置的验证方式相同同步<br>
 * Salt是随机生成的
 * @author jahentao
 * @since 1.0
 */
// 从XML中注入了
public class PasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private String algorithmName = "md5";
    private Integer hashIterations = 2;
    private Boolean useDefinitedSalt = Boolean.FALSE;
    /**
     * 如果使用用户自定义盐，就使用 {@value salt}
     * <p>当然，在设计时，我已经决定使用随机生成的盐了</p>
     */
    private String salt="@zhiwanqian.com";

    public Boolean getUseDefinitedSalt() {
        return useDefinitedSalt;
    }

    public void setUseDefinitedSalt(Boolean useDefinitedSalt) {
        this.useDefinitedSalt = useDefinitedSalt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getSalt() {
        return salt;
    }

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    /**
     * 加密用户密码
     * @param user
     */
    public void encryptPassword(User user) {

        if (user.getPassword()==null) return;

        // 使用随机的盐值
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
//        user.setSalt(salt); // 使用确定的盐值

        String credentialsSalt = useDefinitedSalt ? salt : user.getSalt();

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(credentialsSalt),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
}
